package com.yuxinmuyu.sports_management.interceptors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuxinmuyu.sports_management.bean.LoginUser;
import com.yuxinmuyu.sports_management.bean.entiy.SysUsers;
import com.yuxinmuyu.sports_management.exception.BusinessException;
import com.yuxinmuyu.sports_management.exception.R;
import com.yuxinmuyu.sports_management.service.UserService;
import com.yuxinmuyu.sports_management.utils.JWTUtils;
import com.yuxinmuyu.sports_management.utils.RedisKey;
import com.yuxinmuyu.sports_management.utils.UserUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
    @Autowired
    private UserService userService;
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        if (!(handler instanceof HandlerMethod)) {
            return false;
        }
        //令牌验证
        String token = request.getHeader("Authorization");
        if (ObjectUtils.isEmpty(token)) {
            writeResponse(response, 401, "用户令牌不存在,请重新登陆!");
            return false;
        }
        String userID= JWTUtils.getUserId(token);
        String redisUserInfoKey = String.format(RedisKey.LOGIN_INFO_KEY, userID);
        String userInfoJson = redisTemplate.opsForValue().get(redisUserInfoKey);
        if (ObjectUtils.isEmpty(userInfoJson)) {
            writeResponse(response, 401, "用户信息不存在，请先认证");
            return false;
        }
        try {
            JSONObject json = JSON.parseObject(userInfoJson);
            LoginUser loginUser = new LoginUser();
            loginUser.setUserID(userID);
            loginUser.setUserName(json.getString("userName"));
            loginUser.setDeptID(json.getString("deptID"));
            loginUser.setAvater(json.getString("avater"));
            UserUtil.set(loginUser);
            return true;
        }catch (Exception e)
        {
            throw new BusinessException("当前用户信息解析异常", e);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserUtil.remove();//清除TreadLocal中的数据，防止内存泄露
    }
    private void writeResponse(HttpServletResponse response, int code, String msg) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=UTF-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.write(JSONObject.toJSONString(R.fail(code, msg)));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}
